import React, { Component, Fragment } from 'react';
import { formatMessage, FormattedMessage } from 'umi/locale';
import { Form, Select, Button, message, Switch, Row, Col, Card, Input, Modal } from 'antd';
import { connect } from 'dva';
import styles from './BaseView.less';
import StandardTable from '@/components/StandardTable';
import DescriptionList from '@/components/DescriptionList';
import CusInputNumber from '@/components/CusInputNumber';
import IconButton from '@/components/IconButton';
import WeightRuleTable from '../../Service/WeightRuleTable';
import ShowRuleTable from '../../Service/WeightRuleTable/show';
import get from 'lodash/get';
import { SERVICE_STATUS } from '@/Constants';

const { Description } = DescriptionList;

const FormItem = Form.Item;
const { Option } = Select;

@connect(({ product, loading }) => ({
  currentProduct: product.currentProduct,
  submitting: loading.effects['product/update'],
  createLoading: loading.effects['product/createCalcRules'],
}))
@Form.create()
class WeightRuleView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      mode: 'view',
      calcRuleList: [],
    };
  }
  handleSaveRuleList = val => {
    this.setState({
      calcRuleList: val,
    });
  };

  handleUpdate = () => {
    const { dispatch, form, currentProduct, location } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const { calcRuleList } = this.state;
      calcRuleList.map(val => {
        val.productId = location.query.productId;
      });
      let payload = {
        ...currentProduct,
        ...fieldsValue,
        productCalcRuleList: calcRuleList,
      };
      dispatch({
        type: 'product/update',
        payload: {
          pathParams: {
            id: currentProduct.id,
          },
          data: payload,
        },
      }).then(res => {
        if (res.errorCode === 0) {
          dispatch({
            type: 'product/fetchCurrent',
            payload: {
              pathParams: {
                id: currentProduct.id,
              },
            },
          });
          form.resetFields();
          this.setState({
            mode: 'view',
          });
          message.success('更新成功');
        }
      });
    });
  };

  renderTable = () => {
    const { location } = this.props;
    return (
      <WeightRuleTable
        productId={location.query.productId}
        type="isProduct"
        onSave={this.handleSaveRuleList}
      />
    );
  };

  renderView = () => {
    const { currentProduct, location } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
    };

    let entry = location.query.entry;

    return (
      <div style={{ position: 'relative' }}>
        {(currentProduct.status === SERVICE_STATUS.DRAFT ||
          (!currentProduct.isOnline &&
            currentProduct.status === SERVICE_STATUS.AUDITTED &&
            entry === 'audit')) && (
          <Button
            type="primary"
            style={{ position: 'absolute', right: 20, top: 15, zIndex: 2 }}
            onClick={() => this.setState({ mode: 'edit' })}
          >
            编辑
          </Button>
        )}
        <FormItem label="是否计体积" {...formItemLayout}>
          <Switch checked={currentProduct.isVolume} disabled />
        </FormItem>
        {currentProduct.isVolume && (
          <FormItem label="体&#8197;积&#8197;系&#8197;数&#8197;" {...formItemLayout}>
            {currentProduct.volumeFactor}
          </FormItem>
        )}
        {currentProduct.isVolume && (
          <ShowRuleTable productId={location.query.productId} type="isProduct" />
        )}
      </div>
    );
  };

  renderForm = () => {
    const {
      form: { getFieldDecorator, getFieldValue, getFieldsValue },
      currentProduct,
      submitting,
    } = this.props;
    const { mode, showAdd } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
    };

    return (
      <div>
        <FormItem label="是否计体积" {...formItemLayout}>
          {getFieldDecorator('isVolume', {
            valuePropName: 'checked',
            rules: [{ required: true, message: '不能为空' }],
            initialValue: currentProduct.isVolume,
          })(<Switch />)}
        </FormItem>
        {getFieldValue('isVolume') && (
          <FormItem label="体&#8197;积&#8197;系&#8197;数&#8197;" {...formItemLayout}>
            {getFieldDecorator('volumeFactor', {
              rules: [{ required: true, message: '请输入体积系数' }],
              initialValue: currentProduct.volumeFactor || 6000,
            })(<CusInputNumber max={99999} min={1} style={{ width: 300 }} />)}
          </FormItem>
        )}
        {getFieldValue('isVolume') && (
          <div style={{ marginBottom: 30 }}>{this.renderTable({ show: false })}</div>
        )}
        <Row type="flex">
          <Col span={5} />
          {mode == 'edit' && (
            <Fragment>
              <Button style={{ marginLeft: 130 }} onClick={() => this.setState({ mode: 'view' })}>
                取消
              </Button>
              <Button
                type="primary"
                style={{ marginLeft: 30 }}
                onClick={this.handleUpdate}
                loading={submitting}
              >
                保存
              </Button>
            </Fragment>
          )}
        </Row>
      </div>
    );
  };

  render() {
    const { mode } = this.state;
    let renderer = null;
    if (mode == 'edit') renderer = this.renderForm();
    if (mode == 'view') renderer = this.renderView();
    return <Card bordered={false}>{renderer}</Card>;
  }
}

export default WeightRuleView;
